package com.heima.gateway.filiter;


import com.alibaba.fastjson.JSON;
import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 判断是否登录的过滤器
 */
@Component
@Slf4j
@Order(0)
public class AuthorizeFilter implements GlobalFilter {
    private static ArrayList<String> urlList = new ArrayList<>();

    //定义白名单
    static {
        urlList.add("/login/in");
        urlList.add("/v2/api-docs");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求 响应对象
        ServerHttpRequest request = exchange.getRequest();
        //根据白名单判断是否需要拦截
        String path = request.getURI().getPath();
        for (String url : urlList) {
            if (path.contains(url)) {
                return chain.filter(exchange);
            }
        }
        //对需要拦截的请求判断里面有没有token
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        if (token == null) {
            return writeMessage(exchange, "请先登录");
        }
        try {
            //获取token中的信息
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //判断token是否过期
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i > 0) {
                return writeMessage(exchange, "登录已过期，请重新登录");
            }
            //解析token中的信息
            Integer id = claimsBody.get("id", Integer.class);
            log.info("token网关验证成功，id:{},  URL:{}", id, path);
            //将信息写入请求头，放行
            request.mutate().header("userId", String.valueOf(id));
            exchange.mutate().request(request);
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("token校验失败：{}", e);
            return writeMessage(exchange, "登录校验失败，请重新登录");
        }
    }

    /**
     * 返回错误提示信息
     */
    private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage", message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}
